const express = require('express');
const router = express.Router();
const UserService = require('./user.service');
const { validateUser } = require('./user.validation');
const ResponseFormatter = require('../../../utils/response-formatter');

/**
 * User Controller V2
 * Enhanced user management with improved features
 */

// GET /api/v2/users - Get all users with pagination and filtering
router.get('/', async (req, res, next) => {
  try {
    const {
      page = 1,
      limit = 10,
      search,
      role,
      sort = 'created_at',
      order = 'desc'
    } = req.query;

    const result = await UserService.getAllUsers({
      page: parseInt(page),
      limit: parseInt(limit),
      search,
      role,
      sort,
      order
    });

    // V2 standardized response format
    ResponseFormatter.success(res, result.data, 'Users retrieved successfully');
    // Add pagination headers
    res.set({
      'X-Current-Page': result.pagination.current_page,
      'X-Total-Pages': result.pagination.total_pages,
      'X-Total-Items': result.pagination.total_items,
      'X-Items-Per-Page': result.pagination.items_per_page
    });
  } catch (error) {
    next(error);
  }
});

// GET /api/v2/users/:id - Get user by ID with detailed profile
router.get('/:id', async (req, res, next) => {
  try {
    const user = await UserService.getUserById(req.params.id);
    
    if (!user) {
      return ResponseFormatter.notFound(res, 'User not found');
    }

    ResponseFormatter.success(res, user, 'User retrieved successfully');
  } catch (error) {
    next(error);
  }
});

// POST /api/v2/users - Create user with enhanced validation
router.post('/', validateUser, async (req, res, next) => {
  try {
    const newUser = await UserService.createUser(req.body);
    
    ResponseFormatter.success(res, newUser, 'User created successfully', 201);
  } catch (error) {
    next(error);
  }
});

// PUT /api/v2/users/:id - Update user (enhanced)
router.put('/:id', async (req, res, next) => {
  try {
    const updatedUser = await UserService.updateUser(req.params.id, req.body);
    
    if (!updatedUser) {
      return ResponseFormatter.notFound(res, 'User not found');
    }

    ResponseFormatter.success(res, updatedUser, 'User updated successfully');
  } catch (error) {
    next(error);
  }
});

// DELETE /api/v2/users/:id - Soft delete user
router.delete('/:id', async (req, res, next) => {
  try {
    const result = await UserService.deleteUser(req.params.id);
    
    if (!result) {
      return ResponseFormatter.notFound(res, 'User not found');
    }

    ResponseFormatter.success(res, null, 'User deleted successfully');
  } catch (error) {
    next(error);
  }
});

module.exports = router;